const express = require('express');
const mysqlUtil = require('../../mysql/mysql-util');
const utilFunc = require('../../utilFunc');
const router = express.Router();
// 生成token
const SECRET = 'nikanwoniubibu';
const jwt = require('jsonwebtoken');

router.get('/', (req, res) =>{
    const data = {
        code: 200,
        content: '',
        message: '用户列表'
    }
    res.send(data);
});

// 登录
router.post('/login', (req, res) =>{
    const data = utilFunc.getResponseData();
    const info = req.query;
    const username = info.username;
    const sql1 = `SELECT * FROM users WHERE username='${username}'`;
    
    mysqlUtil.query(sql1, (err, result) => {
        if (err) {
            return console.log('err1');
        }
        if (!result.length) {
            data.content = [];
            data.message = "用户名不存在。";
            data.code = 422;
        } else if (result[0].password !== info.password) {
            data.code = 300;
            data.message = "用户名或密码错误。";
        } else {
            const curentUserInfo = result[0];
            delete curentUserInfo['password'];
            data.message = "欢迎回来！";
            data.code = 200;
            const token = jwt.sign({
                id: curentUserInfo.id
            }, SECRET, {expiresIn: "1h"});
            data.content = { token, data: curentUserInfo };
        }
        res.send(data);
    });
});



router.get('/add', (req, res) =>{
    const data = utilFunc.getResponseData();
    res.send(data);
});

router.get('/edit', (req, res) =>{
    const data = utilFunc.getResponseData();
    res.send(data);
});

router.get('/delete', (req, res) =>{
    const data = utilFunc.getResponseData();
    res.send(data);
});

module.exports = router;